<?php


namespace Modules\Admin\Http\Controllers\Authorization\User;


use Modules\Common\General\Security\Authorization\Manager;
use Modules\Common\Models\AdminUser;
use Modules\Common\Util\Api;

class Retrieve
{
    /**
     * @Route(path=/api/admin/authorization/user)
     */
    public function index()
    {
        $users = AdminUser::whereType(1)->get(['id', 'zh_name', 'mobile', 'type']);
        $m = new Manager();
        $users->each(function ($user) use ($m) {
            $ownPermissionsCount = count($m->getPermissionsForUser($user->id));
            $allPermissionsCount = count($m->getImplicitPermissionsForUser($user->id));
            $ownRolesCount = count($m->getRolesForUser($user->id));
            $allRolesCount = count($m->getImplicitRolesForUser($user->id));

            $user->own_permissions = $ownPermissionsCount;
            $user->all_permissions = $allPermissionsCount;
            $user->own_roles = $ownRolesCount;
            $user->all_roles = $allRolesCount;
        });
        return Api::success($users);
    }


    /**
     * @Route(path=/api/admin/authorization/user/{user_id})
     */
    public function retrieveOne(int $userId)
    {
        $user = AdminUser::find($userId, ['id', 'zh_name']);
        $m = new Manager();
        $permissions=$m->getPermissionsForUserForPresentation($user->id);
        $implicitPermissions= $m->getImplicitPermissionsForUserForPresentation($user->id);
        $roles=$m->getRolesForUserForPresentation($user->id);
        $implicitRoles= $m->getImplicitRolesForUserForPresentation($user->id);

        $user->permissions =$permissions ;
        $user->all_permissions =$implicitPermissions;
        $user->roles = $roles;
        $user->all_roles =$implicitRoles;
        return Api::success($user);
    }


}
